package edu.isistan.soc;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLConnection;

import org.ow2.easywsdl.wsdl.WSDLFactory;
import org.ow2.easywsdl.wsdl.api.Description;
import org.ow2.easywsdl.wsdl.api.InterfaceType;
import org.ow2.easywsdl.wsdl.api.Operation;
import org.ow2.easywsdl.wsdl.api.WSDLException;
import org.ow2.easywsdl.wsdl.api.WSDLReader;
import org.xml.sax.InputSource;

public class WsdlService {

	/**
	 * Counts the number of {@link Operation} for each {@link PortType}, given
	 * an url with a wsdl location.
	 * 
	 * @param wsdlLocation
	 *            The location of the wsdl.
	 * @return The number of operations given by a wsdl.
	 * @throws WSDLException
	 *             If the wsdl cannot be parsed.
	 * @throws MalformedURLException
	 *             The url of the wsdl is not correct.
	 * @throws IOException
	 *             The wsdl file cannot be handled.
	 * @throws URISyntaxException
	 *             The wsdl location is not given correctly.
	 */
	public int count(final String wsdlLocation) throws WSDLException,
			MalformedURLException, IOException, URISyntaxException {

		WSDLReader reader = WSDLFactory.newInstance().newWSDLReader();
		Description description;
		InputStream inputStream;
		URLConnection urlConnection = URI.create(wsdlLocation).toURL()
				.openConnection();
		urlConnection.connect();
		inputStream = urlConnection.getInputStream();
		description = reader.read(new InputSource(inputStream));
		int count = 0;
		for (InterfaceType portType : description.getInterfaces()) {
			StringBuffer sb = new StringBuffer();
			sb.append(portType.getQName().getLocalPart().trim());
			count += portType.getOperations().size();
		}
		return count;
	}
}
